import type {
  Annotation,
  Point,
  RectAnnotation,
  ArrowAnnotation,
  TextAnnotation,
  MosaicAnnotation,
  NumberAnnotation,
  HighlightAnnotation,
  PenAnnotation,
  EraserAnnotation,
} from '@/types/screenshot'

/**
 * 绘制矩形标注
 */
export function drawRect(
  ctx: CanvasRenderingContext2D,
  annotation: RectAnnotation
) {
  const { startPoint, endPoint, color, lineWidth } = annotation
  
  ctx.strokeStyle = color
  ctx.lineWidth = lineWidth
  ctx.strokeRect(
    startPoint.x,
    startPoint.y,
    endPoint.x - startPoint.x,
    endPoint.y - startPoint.y
  )
}

/**
 * 绘制箭头标注
 */
export function drawArrow(
  ctx: CanvasRenderingContext2D,
  annotation: ArrowAnnotation
) {
  const { startPoint, endPoint, color, lineWidth } = annotation
  if (!endPoint) return

  const headLength = 15 + lineWidth * 2 // 箭头长度
  const angle = Math.atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x)

  ctx.strokeStyle = color
  ctx.fillStyle = color
  ctx.lineWidth = lineWidth

  // 绘制箭头线
  ctx.beginPath()
  ctx.moveTo(startPoint.x, startPoint.y)
  ctx.lineTo(endPoint.x, endPoint.y)
  ctx.stroke()

  // 绘制箭头头部
  ctx.beginPath()
  ctx.moveTo(endPoint.x, endPoint.y)
  ctx.lineTo(
    endPoint.x - headLength * Math.cos(angle - Math.PI / 6),
    endPoint.y - headLength * Math.sin(angle - Math.PI / 6)
  )
  ctx.lineTo(
    endPoint.x - headLength * Math.cos(angle + Math.PI / 6),
    endPoint.y - headLength * Math.sin(angle + Math.PI / 6)
  )
  ctx.closePath()
  ctx.fill()
}

/**
 * 绘制文字标注
 */
export function drawText(
  ctx: CanvasRenderingContext2D,
  annotation: TextAnnotation
) {
  const { startPoint, text, color, fontSize } = annotation

  ctx.fillStyle = color
  ctx.font = `${fontSize}px Arial, sans-serif`
  ctx.textBaseline = 'top'

  // 绘制文字背景
  const metrics = ctx.measureText(text)
  const padding = 4
  ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
  ctx.fillRect(
    startPoint.x - padding,
    startPoint.y - padding,
    metrics.width + padding * 2,
    fontSize + padding * 2
  )

  // 绘制文字
  ctx.fillStyle = color
  ctx.fillText(text, startPoint.x, startPoint.y)
}

/**
 * 绘制马赛克标注
 */
export function drawMosaic(
  ctx: CanvasRenderingContext2D,
  annotation: MosaicAnnotation,
  originalCanvas: HTMLCanvasElement
) {
  const { startPoint, endPoint } = annotation
  if (!endPoint) return

  const x = Math.min(startPoint.x, endPoint.x)
  const y = Math.min(startPoint.y, endPoint.y)
  const width = Math.abs(endPoint.x - startPoint.x)
  const height = Math.abs(endPoint.y - startPoint.y)

  const mosaicSize = 10 // 马赛克块大小

  // 获取原始图像数据
  const imageData = ctx.getImageData(x, y, width, height)
  const data = imageData.data

  // 应用马赛克效果
  for (let i = 0; i < height; i += mosaicSize) {
    for (let j = 0; j < width; j += mosaicSize) {
      // 获取块的平均颜色
      let r = 0, g = 0, b = 0, count = 0

      for (let dy = 0; dy < mosaicSize && i + dy < height; dy++) {
        for (let dx = 0; dx < mosaicSize && j + dx < width; dx++) {
          const index = ((i + dy) * width + (j + dx)) * 4
          r += data[index]
          g += data[index + 1]
          b += data[index + 2]
          count++
        }
      }

      r = Math.floor(r / count)
      g = Math.floor(g / count)
      b = Math.floor(b / count)

      // 填充块
      ctx.fillStyle = `rgb(${r}, ${g}, ${b})`
      ctx.fillRect(
        x + j,
        y + i,
        Math.min(mosaicSize, width - j),
        Math.min(mosaicSize, height - i)
      )
    }
  }
}

/**
 * 绘制序号标注
 */
export function drawNumber(
  ctx: CanvasRenderingContext2D,
  annotation: NumberAnnotation
) {
  const { startPoint, number, color, radius } = annotation

  // 绘制圆形背景
  ctx.fillStyle = color
  ctx.beginPath()
  ctx.arc(startPoint.x, startPoint.y, radius, 0, Math.PI * 2)
  ctx.fill()

  // 绘制数字
  ctx.fillStyle = '#FFFFFF'
  ctx.font = `bold ${radius}px Arial`
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.fillText(String(number), startPoint.x, startPoint.y)
}

/**
 * 绘制高亮标注
 */
export function drawHighlight(
  ctx: CanvasRenderingContext2D,
  annotation: HighlightAnnotation
) {
  const { startPoint, endPoint, color } = annotation
  if (!endPoint) return

  ctx.fillStyle = color + '40' // 添加透明度
  ctx.fillRect(
    startPoint.x,
    startPoint.y,
    endPoint.x - startPoint.x,
    endPoint.y - startPoint.y
  )
}

/**
 * 绘制画笔标注
 */
export function drawPen(
  ctx: CanvasRenderingContext2D,
  annotation: PenAnnotation
) {
  const { points, color, lineWidth } = annotation
  if (!points || points.length < 2) return

  ctx.strokeStyle = color
  ctx.lineWidth = lineWidth
  ctx.lineCap = 'round'
  ctx.lineJoin = 'round'

  ctx.beginPath()
  ctx.moveTo(points[0].x, points[0].y)

  for (let i = 1; i < points.length; i++) {
    ctx.lineTo(points[i].x, points[i].y)
  }

  ctx.stroke()
}

/**
 * 绘制橡皮擦效果（通过清除区域）
 */
export function drawEraser(
  ctx: CanvasRenderingContext2D,
  annotation: EraserAnnotation
) {
  const { points, eraserWidth } = annotation
  if (!points || points.length < 2) return

  ctx.globalCompositeOperation = 'destination-out'
  ctx.lineWidth = eraserWidth
  ctx.lineCap = 'round'
  ctx.lineJoin = 'round'

  ctx.beginPath()
  ctx.moveTo(points[0].x, points[0].y)

  for (let i = 1; i < points.length; i++) {
    ctx.lineTo(points[i].x, points[i].y)
  }

  ctx.stroke()
  ctx.globalCompositeOperation = 'source-over'
}

/**
 * 绘制标注的统一入口
 */
export function drawAnnotation(
  ctx: CanvasRenderingContext2D,
  annotation: Annotation,
  originalCanvas?: HTMLCanvasElement
) {
  ctx.save()

  switch (annotation.type) {
    case 'rect':
      drawRect(ctx, annotation as RectAnnotation)
      break
    case 'arrow':
      drawArrow(ctx, annotation as ArrowAnnotation)
      break
    case 'text':
      drawText(ctx, annotation as TextAnnotation)
      break
    case 'mosaic':
      if (originalCanvas) {
        drawMosaic(ctx, annotation as MosaicAnnotation, originalCanvas)
      }
      break
    case 'number':
      drawNumber(ctx, annotation as NumberAnnotation)
      break
    case 'highlight':
      drawHighlight(ctx, annotation as HighlightAnnotation)
      break
    case 'pen':
      drawPen(ctx, annotation as PenAnnotation)
      break
    case 'eraser':
      drawEraser(ctx, annotation as EraserAnnotation)
      break
  }

  ctx.restore()
}

/**
 * 判断点是否在标注内
 */
export function isPointInAnnotation(point: Point, annotation: Annotation): boolean {
  switch (annotation.type) {
    case 'rect':
    case 'highlight':
    case 'mosaic': {
      const { startPoint, endPoint } = annotation as RectAnnotation
      if (!endPoint) return false
      const minX = Math.min(startPoint.x, endPoint.x)
      const maxX = Math.max(startPoint.x, endPoint.x)
      const minY = Math.min(startPoint.y, endPoint.y)
      const maxY = Math.max(startPoint.y, endPoint.y)
      return point.x >= minX && point.x <= maxX && point.y >= minY && point.y <= maxY
    }
    case 'arrow': {
      const { startPoint, endPoint } = annotation as ArrowAnnotation
      if (!endPoint) return false
      // 简化判断：检查点是否在箭头的起点和终点构成的矩形区域内
      const threshold = 10
      const minX = Math.min(startPoint.x, endPoint.x) - threshold
      const maxX = Math.max(startPoint.x, endPoint.x) + threshold
      const minY = Math.min(startPoint.y, endPoint.y) - threshold
      const maxY = Math.max(startPoint.y, endPoint.y) + threshold
      return point.x >= minX && point.x <= maxX && point.y >= minY && point.y <= maxY
    }
    case 'number': {
      const { startPoint, radius } = annotation as NumberAnnotation
      const dx = point.x - startPoint.x
      const dy = point.y - startPoint.y
      return Math.sqrt(dx * dx + dy * dy) <= radius
    }
    case 'text': {
      const { startPoint, fontSize } = annotation as TextAnnotation
      // 简化判断：使用一个固定大小的矩形区域
      return point.x >= startPoint.x && point.x <= startPoint.x + 100 &&
             point.y >= startPoint.y && point.y <= startPoint.y + fontSize
    }
    default:
      return false
  }
}




